package com.hd.crdao;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.hd.crdao.activity.LoginActivity;
import com.hd.crdao.activity.ReleaseActivity;
import com.hd.crdao.base.BaseActivity;
import com.hd.crdao.bean.SearchBean;
import com.hd.crdao.config.Constants;
import com.hd.crdao.fragment.FindFragment;
import com.hd.crdao.fragment.HomeFragment;
import com.hd.crdao.fragment.MyFragment;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.DialogUtils;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.PackageInfoUtils;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.StringUtils;
import com.hd.crdao.utils.UIUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import customview.ConfirmDialog;
import feature.Callback;
import okhttp3.Call;
import util.UpdateAppUtils;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    public RadioGroup mRadioGroup;
    FrameLayout mFrameLayout;
    RadioButton mRbHome;
    RadioButton mRbFind;
    RadioButton mRbRelease;
    RadioButton mRbMy;
    private boolean isExit;
    public String mValue;

    private FragmentTransaction mFragmentTransaction;//fragment事务
    private FragmentManager mFragmentManager;//fragment管理者
    private HomeFragment mHomefragment;
    private FindFragment mFindefragment;
    private MyFragment mMyfragment;
    /**
     * true 表示要强制更新  false 不强制更新
     */
    private boolean isForceUpdate;
    public Dialog mProgressDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);  //注册
        mRadioGroup = (RadioGroup) findViewById(R.id.rg_menu);
        mFrameLayout = (FrameLayout) findViewById(R.id.fragment_container);
        mRbHome = (RadioButton) findViewById(R.id.rb_home);
        mRbFind = (RadioButton) findViewById(R.id.rb_find);
        mRbRelease = (RadioButton) findViewById(R.id.rb_release);
        mRbMy = (RadioButton) findViewById(R.id.rb_my);
        mFragmentManager = getSupportFragmentManager();//获取到fragment的管理对象
    }

    @Override
    protected void initListener() {
        mRbHome.setOnClickListener(this);
        mRbFind.setOnClickListener(this);
        mRbRelease.setOnClickListener(this);
        mRbMy.setOnClickListener(this);
    }

    @Override
    protected void initData() {

        checkAndUpdate();
        //默认设置为第0个
        setIndexSelected(0);


    }

    /**
     * @param index
     */
    public void setIndexSelected(int index) {
        try {

            mFragmentTransaction = mFragmentManager.beginTransaction();
            //显示之前将所有的fragment都隐藏起来,在去显示我们想要显示的fragment
            hideFragment(mFragmentTransaction);
            switch (index) {
                case 0:
                    //如果HomeFragment是null的话,就创建一个
                    if (mHomefragment == null) {
                        mHomefragment = new HomeFragment();
                        //加入事务
                        mFragmentTransaction.add(R.id.fragment_container, mHomefragment);
                    } else {
                        //如果HomeFragment不为空就显示出来
                        mFragmentTransaction.show(mHomefragment);
                    }
                    break;
                case 1:
                    if (mFindefragment == null) {
                        mFindefragment = new FindFragment();
                        //加入事务
                        mFragmentTransaction.add(R.id.fragment_container, mFindefragment);
                    } else {
                        //如果Findefragment不为空就显示出来
                        mFragmentTransaction.show(mFindefragment);
                    }
                    break;
                case 2:
                    if (mMyfragment == null) {
                        mMyfragment = new MyFragment();
                        //加入事务
                        mFragmentTransaction.add(R.id.fragment_container, mMyfragment);
                    } else {
                        //如果MyFragment不为空就显示出来
                        mFragmentTransaction.show(mMyfragment);
                    }
                    break;
                default:
                    break;
            }

            //提交事务
            mFragmentTransaction.commit();
        } catch (IllegalStateException e) {
            ALog.d(e.getMessage());
        } /*finally {
            if (mFragmentTransaction != null) {
                mFragmentTransaction.commitNowAllowingStateLoss();
            }
        }*/
    }


    @Override
    public void onBackPressed() {
        exit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SPUtils.saveString("home_cityName", "");
        EventBus.getDefault().unregister(this);
    }

    /**
     * 如果2秒之内点2次退出就结束程序
     */
    private void exit() {

        if (!isExit) {
            isExit = true;
            MyToast.show("再按一次，退出程序");
            new Timer().schedule(new TimerTask() {

                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ReciveMessage(SearchBean searchBean) {
        ALog.d(searchBean.getValue() + "这样可以拿到数据吧!!!!!!!!!");
        mValue = searchBean.getValue();
    }

    public String getPassMsg() {
        return mValue;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rb_home:
                setIndexSelected(0);
                break;
            case R.id.rb_find:
                setIndexSelected(1);
                break;
            case R.id.rb_release:
                if (SPUtils.getBoolean("hasLogin", false)) {
                    startActivity(new Intent(UIUtils.getContext(), ReleaseActivity.class));
                } else {
                    startActivity(new Intent(UIUtils.getContext(), LoginActivity.class));
                }
                break;
            case R.id.rb_my:
                if (!SPUtils.getBoolean("hasLogin", false)) {
                    startActivity(new Intent(UIUtils.getContext(), LoginActivity.class));
                } else {
                    setIndexSelected(2);
                }

                break;
            default:
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        String check = SPUtils.getString("check", "");
        if (TextUtils.equals(check, "home")) {
            setIndexSelected(0);
            mRadioGroup.check(R.id.rb_home);
            SPUtils.saveString("check", "");
        } else if (TextUtils.equals(check, "find")) {
            setIndexSelected(1);
            mRadioGroup.check(R.id.rb_find);
            SPUtils.saveString("check", "");
        } else {
//            ALog.d("走首页的ELSE");
//            mRadioGroup.check(R.id.rb_home);
        }
    }

    /**
     * 用来隐藏fragment的方法
     *
     * @param fragmentTransaction
     */
    private void hideFragment(FragmentTransaction fragmentTransaction) {
        //如果此fragment不为空的话就隐藏起来
        if (mHomefragment != null) {
            fragmentTransaction.hide(mHomefragment);
        }
        if (mFindefragment != null) {
            fragmentTransaction.hide(mFindefragment);
        }
        if (mMyfragment != null) {
            fragmentTransaction.hide(mMyfragment);
        }
    }

    /**
     * 检测版本是否升级
     * 1表示强制更新, 0 表示不强制更新 现已添加强制更新时,不更新无法操作
     */
    private void checkVersion() {
        mProgressDialog = DialogUtils.createProgressDialog(this,"为不影响新版本的正常使用，需要强制更新");
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        OkHttpUtils.post().url(Constants.VERSION_CONTROL_URL).addParams("appType", "ANDROID")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("无法检测新版本,请检查网络是否连接");
                mProgressDialog.dismiss();
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    //服务器返回的json数据
                    String success = (String) jsonObject.get("success");
                    String message = (String) jsonObject.get("message");
                    String version = (String) jsonObject.get("version");  //服务器版本号
                    String updateContent = (String) jsonObject.get("updateContent");
                    String updateFlag = (String) jsonObject.get("updateFlag");
                    String updateUrl = (String) jsonObject.get("updateUrl");
                    updateContent = StringUtils.dealWithWords(updateContent);
                    if (TextUtils.equals("00", success)) {
                        String packageVersion = PackageInfoUtils.getAppVersionName(MainActivity.this);   //获取本地版本
                        ALog.d("当前的版本号:" + packageVersion);
                        if (packageVersion.compareTo(version) < 0) {   //表示本地的版本是旧版本,需要更新
                            isForceUpdate = TextUtils.equals("1", updateFlag);
                            UpdateAppUtils.from(MainActivity.this)
                                    .checkBy(UpdateAppUtils.CHECK_BY_VERSION_NAME) //更新检测方式，默认为VersionCode
                                    .serverVersionName(version)
                                    .updateInfo(updateContent)
                                    .apkPath(updateUrl)
                                    .downloadBy(UpdateAppUtils.DOWNLOAD_BY_APP) //下载方式：app下载、手机浏览器下载。默认app下载
                                    .isForce(isForceUpdate) //是否强制更新，默认false 强制更新情况下用户不同意更新则不能使用app
                                    .update();
                            if(!isForceUpdate){
                                mProgressDialog.dismiss();
                            }
                        } else {
                            mProgressDialog.dismiss();
                        }
                    } else {
                        MyToast.show(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void checkAndUpdate() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            checkVersion();
        } else {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                checkVersion();
            } else {//申请权限
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }
    }

    //权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    checkVersion();
                } else {
                    new ConfirmDialog(this, new Callback() {
                        @Override
                        public void callback(int position) {
                            if (position == 1) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.parse("package:" + getPackageName())); // 根据包名打开对应的设置界面
                                startActivity(intent);
                            }
                        }
                    }).setContent("暂无读写SD卡权限\n是否前往设置？").show();
                }
                break;
        }

    }

}
